package com.kischang.blog.web.interceptor;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class MyStrutsFilter extends StrutsPrepareAndExecuteFilter {

    String ue =  null;

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) {
        HttpServletRequest request = (HttpServletRequest) req;
        String url = request.getRequestURI();
        try {
            if (url.endsWith("controller.jsp")) {
                chain.doFilter(req, res);
            } else if (url.endsWith("/jsp/config.json")) {
                if(ue == null){
                    ue = "{" +
                            "\"imageActionName\": \"uploadimage\"," +
                            "\"imageFieldName\": \"upfile\"," +
                            "\"imageMaxSize\": 2048000, " +
                            "\"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"]," +
                            "\"imageCompressEnable\": true, " +
                            "\"imageCompressBorder\": 1600, " +
                            "\"imageInsertAlign\": \"none\", " +
                            "\"imageUrlPrefix\": \"" + ((HttpServletRequest) req).getContextPath() +
                            "\",\"imagePathFormat\": \"/imgupload/{yyyy}{mm}{dd}/{time}{rand:6}\" " +
                            "}";
                }
                IOUtils.write(ue, res.getOutputStream());
                res.getOutputStream().flush();
                return;
            } else {
                super.doFilter(req, res, chain);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
